/*
* axios全局配置
*/
import axios from 'axios'
import {message} from 'antd';
import NProgress from 'nprogress'
import store from '../redux/store'
 import {loginOutUserAndToken} from "../redux/actions/login";
import 'nprogress/nprogress.css'


//配置请求拦截器
axios.interceptors.request.use(
    config => {
        //进度条开始
        NProgress.start();
        //从redux中获取之前保存的token
	
        let token = store.getState()?.login?.token;
			// console.log(token)
        if (token) { //如果token存在，就设置到请求头中
            config.headers.Authorization = `bearer ${token}`;
        }
        return config;
    }, error => {
        return Promise.reject(error);
    }
)

//配置响应拦截器
axios.interceptors.response.use(
    response => {
        //进度条结束
        NProgress.done();
        //请求如果成功，走这里
        return response.data;
    }, error => {
        //进度条结束
        NProgress.done();

        if (error.response.status === 401) {//token有问题
            const {status, msg} = error.response.data;
            if (status === 2) {
                //提示消息
                message.error(`${msg}，请重新登录`, 2);
                //分发删除用户信息的action
                store.dispatch(loginOutUserAndToken());
            }
        }else{
            //请求如果失败，提示错误
            message.error(error.message, 2);
        }
        // 中断Promise链
        return new Promise(() => {
        });
    }
)

export default axios

